package com.zunipe.chat;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zunipe.chat.adapter.ChatAdapter;
import com.zunipe.chat.bean.Message;
import com.zunipe.chat.databinding.ActivityMainBinding;
import com.zunipe.chat.service.ChatService;
import com.zunipe.chat.service.ChatServiceCallback;

public class MainActivity extends AppCompatActivity implements ChatServiceCallback, View.OnClickListener {
    ActivityMainBinding binding;
    private ChatAdapter chatAdapter;
    private ChatService.ChatBinder binder;
    private MainViewModel viewModel;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (ChatService.ChatBinder) service;
            binder.registerCallbackListener(MainActivity.this);
            init();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder.unregisterCallbackListener(MainActivity.this);
        }
    };
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Intent intent = new Intent(this, ChatService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        startService(intent);
    }

    private void init() {
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);

        recyclerView = binding.charList;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        chatAdapter = new ChatAdapter(viewModel.messageList.getValue());
        recyclerView.setAdapter(chatAdapter);
        // MessageList发送变化时通知RecyclerView更新
        viewModel.messageList.observe(this, messages -> chatAdapter.notifyItemInserted(messages.size() - 1));

        binding.btnSend.setOnClickListener(this);
        binding.etMessage.setOnClickListener(this);

        binding.etMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.btnSend.setEnabled(s.length() != 0);
            }
        });
    }

    @Override
    public void onMessageReceiver(Message message) {
        if (chatAdapter != null) {
            viewModel.addMessage(message);
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (layoutManager != null) {
                layoutManager.smoothScrollToPosition(recyclerView, null, chatAdapter.getItemCount() - 1);
            }
        }
    }

    @Override
    public void onConnected() {
        //binding.etMessage.setEnabled(true);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_send) {
            String username = ChatApplication.getInstance().getUsername();
            String message = binding.etMessage.getText().toString();
            if (!message.isEmpty()) {
                if (message.charAt(0) == '/') {
                    long time = System.currentTimeMillis();
                    binder.sendMessage(new Message(1, message.substring(1), username, time));
                    binding.etMessage.setText("");
                } else {
                    long time = System.currentTimeMillis();
                    binder.sendMessage(new Message(0, message, username, time));
                    binding.etMessage.setText("");
                }
            }
        } else if (id == R.id.et_message) {
            new Handler().postDelayed(() -> {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    layoutManager.smoothScrollToPosition(recyclerView, null, chatAdapter.getItemCount() - 1);
                }
            }, 100);
        }
    }
}